package com.example.bishe.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.bishe.entity.Photo;
import com.example.bishe.entity.Record;
import com.example.bishe.entity.RecordChildren;
import com.example.bishe.mapper.PhotoMapper;
import com.example.bishe.mapper.RecordChildrenMapper;
import com.example.bishe.mapper.RecordMapper;
import com.example.bishe.service.RecordChildrenService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.bishe.util.RedisUtil;
import com.example.bishe.util.xorEncrypt;
import com.example.bishe.web.c.dto.AddRecord;
import com.example.bishe.web.c.vo.BarVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author LDH
 * @since 2022/11/30
 */
@Service
@Slf4j
public class RecordChildrenServiceImpl extends ServiceImpl<RecordChildrenMapper, RecordChildren> implements RecordChildrenService {

    @Autowired
    private RecordChildrenMapper recordChildrenMapper;
    @Autowired
    private RecordMapper recordMapper;
    @Autowired
    private PhotoMapper photoMapper;
    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private PlatformTransactionManager platformTransactionManager;
    @Autowired
    private TransactionDefinition transactionDefinition;

    /**
    * 功能描述: 用户查询二级记录列表
    * @Param: [pageNum, pageSize, recordId, time, show]
    * @return: com.baomidou.mybatisplus.core.metadata.IPage<com.example.bishe.entity.RecordChildren>
    * @Author: LDH
    * @Date: 2023/04/20
    */
    @Override
    public IPage<AddRecord> gePage(int pageNum, int pageSize, Long recordId, String time, Integer show) {
        Page<RecordChildren> page = new Page<>(pageNum,pageSize);
        IPage<AddRecord> iPage = recordChildrenMapper.getPage(page,time,recordId,show);
        iPage.getRecords().forEach(e -> {
            if (e.getIsShow() == 0) {
                e.setImages(photoMapper.getImages(e.getId()).stream().map(p -> p = xorEncrypt.xor(p,redisUtil.getChar("openId"))).collect(Collectors.toList()));
                e.setText(xorEncrypt.xor(e.getText(),redisUtil.getChar("openId")));
            } else {
                e.setImages(photoMapper.getImages(e.getId()));
            }
        });
        return iPage;
    }

    /**
    * 功能描述: 新建记录
    * @Param: [recordChildren]
    * @return: int
    * @Author: LDH
    * @Date: 2023/04/20
    */
    @Override
    public int add(AddRecord addRecord) {
        if (recordChildrenMapper.selectByTime(addRecord.getRecordId()).size() != 0){
            log.warn("已有当天日期的记录，无法新建");
            return -1;
        }
        Record record = recordMapper.selectById(addRecord.getRecordId());
        if (record != null && record.getType() == 1 && recordChildrenMapper.selectByState(addRecord.getRecordId()) != null){
            log.warn("当前有正在进行中的记录，无法新建");
            return -2;
        }

        // 如果是隐性记录， 则加密内容
        System.out.println("openid:"+redisUtil.get("openId"));
        if (addRecord.getIsShow() == 0) addRecord.setText(xorEncrypt.xor(addRecord.getText(),redisUtil.getChar("openId")));
        recordChildrenMapper.insert(addRecord);
        if (addRecord.getImages().size() != 0){
            addRecord.getImages().forEach(e -> {
                Photo photo = new Photo();
                photo.setComeId(addRecord.getId());
                photo.setUrl(addRecord.getIsShow() == 0 ? xorEncrypt.xor(e,redisUtil.getChar("openId")) : e);
                photoMapper.insert(photo);
            });
        }
        return 0;
    }

    /**
    * 功能描述: 修改记录
    * @Param: [addRecord]
    * @return: int
    * @Author: LDH
    * @Date: 2023/04/20
    */
    @Override
    public int update(AddRecord addRecord) {
        Record record = recordMapper.selectById(addRecord.getRecordId());
        if (addRecord.getIsShow() == 0) addRecord.setText(xorEncrypt.xor(addRecord.getText(),redisUtil.getChar("openId")));
        // 如果是记录-有规律型，可以跨时间修改记录
        if (record.getType() == 1){
            recordChildrenMapper.updateById(addRecord);
            return 0;
        }
        // 要修改的记录时间
        String time = addRecord.getCreateTime().toString();
        // 默认的年月日的格式. yyyy-MM-dd
        String timeFormat = "yyyy-MM-dd";
        // 当前时间
        Date now = new Date();
        SimpleDateFormat sf = new SimpleDateFormat(timeFormat);
        //获取今天的日期
        String nowDay = sf.format(now);
        // 如果修改的记录不是当天时间，无法修改
        if (!time.contains(nowDay)){
            log.warn("非当天记录，无法修改");
            return -1;
        }

        recordChildrenMapper.updateById(addRecord);
        return 0;
    }

    /**
    * 功能描述: 删除记录
    * @Param: [ids]
    * @return: int
    * @Author: LDH
    * @Date: 2023/04/20
    */
    @Override
    public int delete(List<Long> ids) {
        return ids.size() - recordChildrenMapper.deleteBatchIds(ids);
    }

    /**
    * 功能描述: 获取日历日期
    * @Param: [recordId, year, month]
    * @return: java.util.List<com.example.bishe.entity.RecordChildren>
    * @Author: LDH
    * @Date: 2023/05/03
    */
    @Override
    public List<RecordChildren> getCalendar(Long recordId, Integer year, Integer month) {
        String start = year + "-" + month + "-01";
        String end = year + "-" + (month+1)%12 + "-01";
        return recordChildrenMapper.getCalendar(recordId,start,end);
    }

    /**
    * 功能描述: 分页查询二级记录，再转换成条状数据格式返回
    * @Param: [pageNum, pageSize, recordId, show]
    * @return: java.util.List<com.example.bishe.web.c.vo.BarVO>
    * @Author: LDH
    * @Date: 2023/05/03
    */
    @Override
    public List<BarVO> getBar(int pageNum, int pageSize, Long recordId, Integer show) {
        Page<RecordChildren> page = new Page<>(pageNum,pageSize);
        IPage<RecordChildren> iPage = recordChildrenMapper.getBarPage(page,recordId,show);
        return new BarVO().setBar(iPage.getRecords());
    }
}
